import { Player } from "../extra/player"
import Basic from "@/global"
import { Battle } from "./Battle"
import { Fightcard } from "./Character"
import { ipairs } from "@/utils/lua"
import { table } from "@/utils/lua/table"

export class FightPlayer {
  id: number
  name: string
  side: 'A' | 'B'
  vocation: number
  cardback: number
  mana!: number
  rndtime: number = 0
  prelimit: number
  fields: (Fightcard | undefined)[] = [undefined, undefined, undefined]
  battle: Battle
  opponent!: this
  global!: Fightcard

  constructor(player: Player, battle: Battle) {
    this.id = player.id
    this.name = player.name
    this.side = player.side
    this.vocation = player.vocation
    this.cardback = player.cardback
    this.mana = player.mana || 0
    this.rndtime = player.rndtime
    this.side = player.side
    this.prelimit = (battle.battletype === Basic.constant.research_battle) ? 2 : 3
    this.battle = battle
    // 创建全局卡牌（挂全局光环之类的）
    this.global = battle.createCharacter(this, undefined, player.global)
    player.fields?.forEach((card, i) => {
      if (card.id) {
        this.fields[i] = battle.createCharacter(this, undefined, card)
      }
    })
  }
  getTar(card, side: 'ally' | 'self' | 'other' | 'friend' | 'enemy' | 'both', range?) {
    let rangeTars: (Fightcard | undefined)[] = []

    const byField = (field) => {
      if (this.fields[field]) {
        rangeTars.push(this.fields[field])
      }
      if (this.opponent.fields[field]) {
        rangeTars.push(this.opponent.fields[field])
      }
    }
    for (const [i, field] of ipairs(this.battle.fields)) {
      if (!range || table.keyof(range, field)) {
        byField(i);
      }
    }
    let finalTars: (Fightcard | undefined)[] = []
    for (let [_, fightcard] of Object.entries(rangeTars)) {
      if (!fightcard) continue
      if (side === "self") {
        if (fightcard.id === card.id) {
          finalTars.push(fightcard)
        }
      }

      if (side === "friend") {
        if (fightcard.player === this) {
          finalTars.push(fightcard)
        }
      }

      if (side === "enemy") {

        if (fightcard.player !== this) {
          finalTars.push(fightcard)
        }
      }

      if (side === "both") {
        finalTars[fightcard.id] = fightcard
      }

      if (side === "ally") {

        if (fightcard.player === this && fightcard.id !== card.id) {
          finalTars.push(fightcard)
        }
      }

      if (side === "other") {
        if (fightcard.id !== card.id) {
          finalTars.push(fightcard)
        }
      }
    }

    return finalTars as (Fightcard)[]
  }
  getPos(tar: Fightcard): [string?, number?] {
    if (tar === this.global) {
      return ["global"]
    }
    for (let [field, fightcard] of Object.entries(this.fields)) {
      if (tar.id === fightcard?.id) {
        return ["field", +field]
      }
    }
    return []
  }
}